from infos import db
from infos.models import News, Comment, CommentLike, User
from infos.modules.news import news_blu
from flask import render_template, current_app, jsonify, abort, g, request
from infos.utils.commons import login_in
from infos.utils.response_code import RET


# 关注
@news_blu.route('/followed_user', methods=['POST'])
@login_in
def follow():
    user = g.user
    if not user:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    action = request.json.get('action')
    user_id = request.json.get('user_id')

    if all in ([action, user_id]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    if action not in ("follow", "unfollow"):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    try:
        other = User.query.get(user.id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询失败')

    if action == 'follow':
        if other not in user.followed:
            user.followed.append(other)
        else:
            return jsonify(errno=RET.OK, errmsg='已关注')
    else:
        if other in user.followed:
            user.followed.remove(other)
        else:
            return jsonify(errno=RET.OK, errmsg='未关注')

    return jsonify(errno=RET.OK, errmsg='成功')


# 评论点赞
@news_blu.route('/comment_like', methods=['POST'])
@login_in
def comment_like():
    user = g.user
    # 验证登录
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')
    # 获取ajax 中的参数
    comment_id = request.json.get('comment_id')
    action = request.json.get('action')

    # 验证参数是否存在
    if all in ([comment_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 验证action 中是否有add,remove状态
    if action not in ["add", "remove"]:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    try:
        comment_id = int(comment_id)  # 将comment_id转成int类型
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 查询数据库中是否有comment_id
    try:
        comment = Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='参数错误')

    # 判断action 状态,并查询用户id 点赞id的所有数据
    if action == 'add':
        comment_likes = CommentLike.query.filter(CommentLike.user_id == user.id,
                                                 CommentLike.comment_id == comment_id).all()
        if not comment_likes:  # 用户点赞数据未空就执行点赞
            comment_likes = CommentLike()
            comment_likes.user_id = user.id
            comment_likes.comment_id = comment_id
            db.session.add(comment_likes)
            comment.like_count += 1
    else:
        comment_likes = CommentLike.query.filter(CommentLike.user_id == user.id,
                                                 CommentLike.comment_id == comment_id).all()
        if comment_likes:  # 用户点赞数据未空就执行取消点赞
            for comment_like in comment_likes:
                db.session.delete(comment_like)
                comment.like_count -= 1

    return jsonify(errno=RET.OK, errmsg='成功')


# 评论
"""
    1.校验
    2.获取ajax 中的参数
    3.获取数据
    4.将评论存入数据库
"""


@news_blu.route('/news_comment', methods=['POST'])
@login_in
def comment_list():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')

    news_id = request.json.get('news_id')
    comment_content = request.json.get('comment')
    parent_id = request.json.get('parent_id')

    try:
        news_id = int(news_id)
        if parent_id:
            parent_id = int(parent_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)

        return jsonify(errno=RET.DBERR, errmsg='数据库错误')

    if not news:
        return jsonify(errno=RET.DATAERR, errmsg='查询错误')

    comment = Comment()
    comment.news_id = news_id
    comment.user_id = user.id
    comment.content = comment_content
    if parent_id:
        comment.parent_id = parent_id

    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='存入失败')

    return jsonify(errno=RET.OK, errmsg='成功', data=comment.to_dict())


# 收藏
# """
#     1.获取ajax中的收藏状态
#     2.校验参数
#     3.判断收藏状态
# """
@news_blu.route('/news_collect', methods=['POST'])
@login_in
def news_collect():
    user = g.user
    # 1.获取ajax中的收藏状态
    news_id = request.json.get('news_id')
    collection = request.json.get('action')

    # 2.校验参数
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')
    if all in ([news_id, collection]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    try:
        news_id = int(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    if collection not in ('collect', 'cancel_collect'):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')
    if not news:
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')
    # 3.判断收藏状态
    if collection == 'collect':
        if news not in user.collection_news:  # 收藏
            user.collection_news.append(news)
    if collection == 'cancel_collect':
        if news in user.collection_news:  # 取消收藏
            user.collection_news.remove(news)

    return jsonify(errno=RET.OK, errmsg='成功')


# 新闻详情
@news_blu.route('/<int:news_id>')
@login_in
def news_detail(news_id):
    """
    新闻详情
    :param news_id:
    :return:
    """
    user = g.user
    # 新闻点击排行榜
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(6)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询新闻异常')
    # 判断查询结果是否存在
    if not news_list:
        return jsonify(errno=RET.NODATA, errmsg='新闻数据不存在')
    # 遍历查询排行新闻结果
    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_basic_dict())

    try:
        news = News.query.filter(News.id == news_id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库不存在')
    news.clicks += 1
    if not news:
        abort(404)

    # 收藏状态
    is_collected = False
    # 关注
    is_followed = False
    if user:
        if news in user.collection_news:
            is_collected = True
        else:
            is_collected = False

        if news in user.followed:
            is_followed = True
        else:
            is_followed = False

    # 评论
    try:
        comments = Comment.query.filter(Comment.news_id == news_id).order_by(
            Comment.create_time.desc())
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库错误')

    # 点赞
    comment_id_list = [comment.id for comment in comments]  # 用列表表达式遍历循环取到comment.id(评论编号)
    comment_like_list = []  # 这个空列表用于储存comment_id (评论点赞的编号)
    if user:
        try:
            # 验证完用户登录,再查询出user.id(用户id),comment_id(评论点赞的编号)的对象
            comment_lists = CommentLike.query.filter(CommentLike.user_id == user.id,
                                                     CommentLike.comment_id.in_(comment_id_list)).all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='数据库错误')
        comment_like_list = [comment_like.comment_id for comment_like in
                             comment_lists]  # 将comment_lists 对象遍历后赋值给comment_like_list

    comment_list = []  # 该空列表储存to_dict()里的字典
    for comment in comments:
        comment_dict = comment.to_dict()
        comment_dict['is_like'] = False
        if comment.id in comment_like_list:
            comment_dict['is_like'] = True
        comment_list.append(comment_dict)
    data = {
        'user': user.to_dict() if user else None,
        'news_dict_list': news_dict_list,
        'news': news.to_dict(),
        'is_collected': is_collected,
        'comments': comment_list,
        'is_followed': is_followed
    }
    return render_template('news/detail.html', data=data)
